package com.itqf.service.impl;

import com.itqf.dao.CartDao;
import com.itqf.dao.ProductDao;
import com.itqf.dao.impl.CartDaoImpl;
import com.itqf.dao.impl.ProductDaoImpl;
import com.itqf.entity.Cart;
import com.itqf.entity.Product;
import com.itqf.service.CartService;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.List;

public class CartServiceImpl implements CartService {

    //初始化dao层对象
    private static CartDao cartDao = new CartDaoImpl();
    private static ProductDao productDao = new ProductDaoImpl();

    @Override
    public void createCart(int uid, String pid) throws SQLException, InvocationTargetException, IllegalAccessException {

        //1.判断是否已经存在商品信息
       Cart cart =  cartDao.hasCart(uid,pid);
        if (cart != null) {
            //添加过了购物车
            // 2.存在相同的商品信息，则修改数量和小计
            cart.setCnum(cart.getCnum()+1);
            cartDao.updateCart(cart);
        }else{
            //3.如果不存在，添加即可
            //1.根据商品id查询商品
            Product product = productDao.selectProductByPid(pid);

            //创建新的对象，存入数据
            cart = new Cart();

            cart.setCnum(1);

            cart.setPid(Integer.parseInt(pid));

            cart.setProduct(product);

            cart.setUid(uid);

            cartDao.insertCart(cart);
        }



    }

    @Override
    public List<Cart> findAll(int uid) throws IllegalAccessException, SQLException, InvocationTargetException {

        List<Cart> carts = cartDao.selectCartsByUid(uid);
        return carts;
    }

    @Override
    public void deleteCartByCid(String cid) throws SQLException {
        cartDao.deleteCartByCid(cid);
    }

    @Override
    public void updateCartByCid(String cid, String price, String cnum) throws SQLException {

        BigDecimal cnumbig = new BigDecimal(cnum);

        BigDecimal pricebig = new BigDecimal(price);

        BigDecimal count = pricebig.multiply(cnumbig);

        cartDao.updateByCid(count,cnumbig,cid);
    }

    @Override
    public void clearCart(String uid) throws SQLException {

        cartDao.deletCartByUid(uid);
    }


}
